import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasLogin: false,
		loginProvider: "",
		openid: null,

		userInfo : {},

		URL : {
			defaultImg : 'https://img.hidlq.com/image/shop/default.jpeg',
			shareBgImg : 'https://img.hidlq.com/image/shop/sharebg.png',
			logoImg : 'https://img.hidlq.com/image/shop/qmlogo.png',
			shop : 'https://shop.hidlq.com/#/',
			api : 'https://api.hidlq.com/',
		},

	},
	getters : {
		URL : state => state.URL,
		openid : state => state.openid,
		userInfo : state => state.userInfo,
	},
	mutations: {
		login(state, provider) {
			state.hasLogin = true;
			state.loginProvider = provider;
		},
		logout(state) {
			state.hasLogin = false
			state.openid = null
		},
		setOpenid(state, openid) {
			state.openid = openid
		},
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo;
		},
	},


	actions: {

		getUserInfo : async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.userInfo.nickName != undefined ) {
					resolve(state.userInfo);
				} else {

					//#ifdef H5
						const info = {
							nickName : "dlq测试",
							avatarUrl : 'http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTIWd4ibJ7fygdZeYq0KmrNFNkzTngiae8hGE3XVjPMQKjibQJIXagMcrqewKskbs6r8DiapXibNJVIwqyQ/132',
						};
						commit('setUserInfo', info);
						resolve(info);
					//#endif

					

					//#ifndef H5
					uni.getUserInfo({
						success: (data) => {
							commit('setUserInfo', data.userInfo);
							resolve(data.userInfo);
						},
						fail: (err) => {
							console.log('uni.getUserInfo 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					});
					//#endif
				}
			});
		},

		// lazy loading openid
		getUserOpenId: async function ({
			commit,
			state
		}) {
			return await new Promise((resolve, reject) => {
				if (state.openid) {
					resolve(state.openid)
				} else {
					uni.login({
						success: (data) => {
							commit('login');
							uni.getUserInfo({
			            		success: (res) => {
			            			console.log('userinfo');
			            			console.log(res);
				              		//this.userInfo = res.userInfo
				            	}
				          	})

							// console.log('data');
							// console.log(data);
							// setTimeout(function () { //模拟异步请求服务器获取 openid
							// 	const openid = '123456789'
							// 	console.log('uni.request mock openid[' + openid + ']');
							// 	commit('setOpenid', openid)
							// 	resolve(openid)
							// }, 1000)
						},
						fail: (err) => {
							console.log('uni.login 接口调用失败，将无法正常使用开放接口等服务', err)
							reject(err)
						}
					})
				}
			})
		}
	}
})

export default store
